package com.vfa.vocaburay;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import com.vfa.test.AnswerE;
import com.vfa.test.QuestionData;
import com.vfa.test.QuestionE;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class actTestExam extends Activity{
	
	private int totalTime;
    private Timer timerTask;
    private TextView timeCountDown;
    public int score = 0;

	LinearLayout lnearAnsewer;
	TextView txvQuestion;
	
	
	public ArrayList<QuestionE> listQuestion ;
	QuestionData questiondata;
	private ArrayList<AnswerE> listAnswer ;
	
	private int CurrenQuestionID = 0;
	private RadioGroup grpAnswer;
	
	int[] userchecked;
	int[] rightanswer;
	int numberQuestion;
	Button btnDone;
	Button btnPrev;
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.test_exam);
		
		Bundle bundle = getIntent().getExtras();
		numberQuestion = bundle.getInt("Numberquestion");
		MapLayout();
	
		questiondata = new QuestionData(this);
		
		listQuestion = QuestionData.getQuestion(0);
		userchecked = new int[numberQuestion];
		rightanswer = new int[numberQuestion];
		
		Log.i("TrungTT","size question:"+listQuestion.size());
		
		loadQuestion();
		
		
		
		totalTime = numberQuestion * 60;
		timeCountDown = (TextView) findViewById(R.id.tvTimer);
		timeCountDown.setTextColor(Color.BLUE);
		new CountDown();
		
	}
	
	private void MapLayout()
	{
		lnearAnsewer = (LinearLayout)findViewById(R.id.lnearAnserwer);		
		txvQuestion = (TextView)findViewById(R.id.txvQuestion);
		
		btnDone = (Button) findViewById(R.id.btnDone);
		Button btnNext = (Button)findViewById(R.id.btnNext);
		grpAnswer = new  RadioGroup(getApplicationContext());
		
		btnNext.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				if((CurrenQuestionID + 1) >= numberQuestion)
				{
					btnDone.setVisibility(View.VISIBLE);
					return; 
				}
				CurrenQuestionID++;
				loadQuestion();

			}
		});
		
		btnPrev = (Button) findViewById(R.id.btnPrev);
		
		btnPrev.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(CurrenQuestionID <= 0 ){
					return;
				}
				CurrenQuestionID--;
				loadQuestion();
			}
		});
		
		btnDone.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				AlertDialog.Builder bd = new AlertDialog.Builder(actTestExam.this);
				bd.setMessage("Are you sure you want to finish the test?").setCancelable(false)
				.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Done();
						
					}
				});
				bd.setNegativeButton("No", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
						
					}
				}).show();
				
			}
		});
	}
	
	public void loadQuestion()
	{

		QuestionE question = listQuestion.get(CurrenQuestionID);
		txvQuestion.setText("Q"+(CurrenQuestionID +1)+". "+question.getQuestion());	
		listAnswer = QuestionData.getAnswer(question.getQuestionId());
		int rs = 1;
		int ketqua = 0;
			
		lnearAnsewer.removeView(grpAnswer);
		grpAnswer = new RadioGroup(getApplicationContext());
		grpAnswer.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				Log.i("TrungTT","check id:"+checkedId);
				userchecked[CurrenQuestionID] = checkedId;
			}
		});

		int id = 0;
		for(AnswerE answer:listAnswer)
		{
			id++;
			RadioButton rdo = new RadioButton(getApplicationContext());
			rdo.setId(id);
			rdo.setText(answer.getAnswer());
			grpAnswer.addView(rdo);
			int temp = answer.getRiro();
			if(temp == 1){
				ketqua = rs;
			}
			rs++;
		}
		rightanswer[CurrenQuestionID] = ketqua;
		Log.i("AnhTH", "rightAnswer:"+rightanswer[CurrenQuestionID]);
		
		RadioButton rdoUserHasChecked =  (RadioButton)grpAnswer.findViewById(userchecked[CurrenQuestionID]);
		if(rdoUserHasChecked != null) rdoUserHasChecked.setChecked(true);
		
		lnearAnsewer.addView(grpAnswer);
		
	}
	

    @Override
    public void onBackPressed() {
        newWordDialog();
        // return;
    }

    private void newWordDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Test is on progress !").setCancelable(false)
                .setPositiveButton("Quit",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                timerTask.cancel();
                                actTestExam.this.finish();
                            }
                        }).setNegativeButton("Back to Test",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
        AlertDialog alert = builder.create();
        alert.show();
    }
	
	private void Done() {
		timerTask.cancel();
		for(int i = 0; i < userchecked.length; i++){
			if(userchecked[i] == rightanswer[i]){
				score++;
			}
		}
		Log.i("AnhTh", "Score:"+score);
		Intent i = new Intent(getApplicationContext(), ResultTest.class);
		i.putExtra("NumberQuestion", numberQuestion);
		i.putExtra("Score", score);
		startActivity(i);
		actTestExam.this.finish();
		
	}
	

	class DisplayCountdown extends TimerTask {

        public void run() {

            if (totalTime > 0) {

                refreshTextHandler.sendMessage(new Message());
                totalTime--;

            } else {
                Done();
            }

        }
    }

    public class CountDown {

        public CountDown() {

            timerTask = new Timer();
            timerTask.schedule(new DisplayCountdown(), 0, 1000);

        }

    }

    Handler refreshTextHandler = new Handler() {
        public void handleMessage(Message msg) {
            int minutes = totalTime / 60;
            int seconds = totalTime % 60;
            String minutesText = "";
            String secondsText = ""; 
            if (minutes == 0 && seconds < 30) {
                timeCountDown.setTextColor(Color.RED);
            }
            // change time
            if (minutes < 10)
                minutesText = "0" + minutes;
            else
                minutesText = "" + minutes;
            if (seconds < 10)
                secondsText = "0" + seconds;
            else
                secondsText = "" + seconds;

            timeCountDown.setText(minutesText + ":" + secondsText);

        }
    };
	

	
}
